package com.school_admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.school_admin.config.Result;
import com.school_admin.entity.Like;
import com.school_admin.entity.Operation;
import com.school_admin.mapper.PostMapper;
import com.school_admin.service.impl.LikeServiceImpl;
import com.school_admin.service.impl.OperationServiceImpl;
import com.school_admin.service.impl.PostServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author
 * @since 2024-03-18
 */
@RestController
@RequestMapping("/like")
public class LikeController {

    private final LikeServiceImpl likeService;
    private final PostMapper postMapper;
    private final OperationServiceImpl operationService;
    @Autowired
    public LikeController(LikeServiceImpl likeService, PostMapper postMapper, OperationServiceImpl operationService) {
        this.likeService = likeService;
        this.postMapper = postMapper;
        this.operationService = operationService;
    }

    @PostMapping("createPostLike")
    public Result<String> createPostLike(Like like) {
        /*
            TODO 1.  获取前端传递的参数
            TODO 2.  调用service层方法
            TODO 3.  判断该用户是否点赞
            TODO 4.  返回结果
         */
        LambdaQueryWrapper<Like> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Like::getUid, like.getUid());
        Like likeOne = likeService.getOne(wrapper);
        if (likeOne != null) {
            return Result.fail("您已经点过赞了");
        } else {
            boolean isLike = likeService.save(like);
            // 更新帖子点赞量
            postMapper.updatePostLikeCount(1,like.getPostId());
            // 记录用户操作行为
//            Operation operation = new Operation();
//            operation.setUid(Integer.valueOf(like.getUid()));
//            operation.setPostId(Integer.valueOf(like.getPostId()));
//            operation.setType(0);
//            operationService.recordOperation(operation);
            // 返回结果
            return  isLike ? Result.success("点赞成功") : Result.fail("系统消息: 点赞失败");
        }
    }
}
